package com.kx.center.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.kx.center.auth.Authentication;
import com.kx.center.entity.Account;
import com.kx.center.entity.Food;
import com.kx.center.entity.FoodCategory;
import com.kx.center.entity.FoodType;
import com.kx.center.entity.StoreAppAccount;
import com.kx.center.entity.StoreInfo;
import com.kx.center.entity.query.QueryFoodCategory;
import com.kx.center.entity.query.QueryResult;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.service.FoodService;
import com.kx.center.service.StoreAppAccountService;
import com.kx.center.service.StoreManagerService;
import com.kx.center.util.JSONParser;
import com.kx.center.util.Response;

@Controller
@RequestMapping("/food")
public class FoodController extends CommonController {

	@Autowired
	FoodService foodService;
	@Autowired
	StoreAppAccountService storeAppAccountService;
	@Autowired
	private StoreManagerService storeManagerService;

	// 添加食品分类
	@RequestMapping(value = "category/add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String category_add(HttpServletRequest request) throws Exception {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String name = StringUtils.trimToEmpty(request.getParameter("name"));
		String weight = StringUtils.trimToEmpty(request.getParameter("weight"));

		if (StringUtils.isEmpty(name) || StringUtils.isEmpty(weight)) {
			return Response.error(MessageCode.NO_DATA, "未知的请求数据");
		}

		FoodCategory result = foodService.findFoodCategoryByName(name,
				account.getCompanyId());
		if (result != null) {
			return Response.error(MessageCode.FOODCATEGORY_IS_EXITS);
		}

		try {
			Integer.parseInt(weight);
		} catch (Exception e) {
			return Response.error(MessageCode.NO_DATA, "输入权重值有误");
		}

		FoodCategory foodCategory = new FoodCategory();
		foodCategory.setName(name);
		foodCategory.setWeight(NumberUtils.toInt(weight));
		foodCategory.setCompanyId(account.getCompanyId());
		foodCategory.setOperatorId(account.getOperatorId());
		foodCategory.setStatus(1);
		foodService.insertFoodCategory(foodCategory);

		return Response.success("食品分类添加成功");
	}

	// 食品分类列表
	@RequestMapping(value = "category/list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String category_list(HttpServletRequest request) throws Exception {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		Integer page, pageSize;
		QueryFoodCategory queryFoodCategory = new QueryFoodCategory();

		String sortBy = request.getParameter("sortBy");
		String sortMethod = request.getParameter("sortMethod");

		page = NumberUtils.toInt(request.getParameter("page_num"));
		pageSize = NumberUtils.toInt(request.getParameter("page_size"));

		if (StringUtils.isBlank(sortBy))
			sortBy = "weight";

		if (StringUtils.isBlank(sortMethod))
			sortMethod = "desc";

		queryFoodCategory.setSortBy(sortBy);
		queryFoodCategory.setSortMethod(sortMethod);
		queryFoodCategory.setPage(page);
		queryFoodCategory.setPageSize(pageSize);
		queryFoodCategory.setCompanyId(account.getCompanyId());
		queryFoodCategory.setStatus(1);

		QueryResult result = foodService.queryFoodCategory(queryFoodCategory);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("page", result.getPage());
		map.put("pageSize", result.getPageSize());
		map.put("totalRecord", result.getTotalRecord());
		map.put("data", result.getData());

		return Response.success(map);
	}

	// 编辑食品分类
	@RequestMapping(value = "category/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String category_edit(HttpServletRequest request) throws Exception {
		
		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String name = StringUtils.trimToEmpty(request.getParameter("name"));
		String weight = StringUtils.trimToEmpty(request.getParameter("weight"));
		String id = StringUtils.trimToEmpty(request.getParameter("id"));
		
		if (StringUtils.isEmpty(name) || StringUtils.isEmpty(weight)) {
			return Response.error(MessageCode.NO_DATA, "未知的请求数据");
		}

		FoodCategory foodCategory = new FoodCategory();
		foodCategory.setId(Integer.parseInt(id));
		foodCategory.setName(name);
		foodCategory.setWeight(Integer.parseInt(weight));
		foodCategory.setOperatorId(account.getOperatorId());
		foodService.updateFoodCategoryById(foodCategory);

		return Response.success("食品分类修改成功");
	}
	
	// 删除食品分类
	@RequestMapping(value = "category/delete", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String category_delete(HttpServletRequest request) throws Exception {

        Account account = this.getCommonUserAccount(request);
        if(account == null){
            return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
        }

    	String id = request.getParameter("id");
    	
    	List<Food> list = foodService.findFoodByCategoryId(Integer.parseInt(id));
		for(Food item : list){
			if(item.getStatus() ==1 ){
				return Response.error(MessageCode.REQUEST_ERROR);
			}
		}
		
		foodService.deleteFoodCategoryById(account, Integer.parseInt(id));

		return Response.success("食品分类删除成功!");
	}

	// 添加食品规格
	@RequestMapping(value = "type/add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String type_add(HttpServletRequest request) throws Exception {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String unit = StringUtils.trimToEmpty(request.getParameter("unit"));

		if (StringUtils.isEmpty(unit)) {
			return Response.error(MessageCode.NO_DATA, "未知的请求数据");
		}

		FoodType result = foodService.findFoodTypeByName(unit,
				account.getCompanyId());
		if (result != null) {
			return Response.error(MessageCode.FOODTYPE_IS_EXITS);
		}

		FoodType foodType = new FoodType();
		foodType.setCompanyId(account.getCompanyId());
		foodType.setOperatorId(account.getOperatorId());
		foodType.setUnit(unit);
		foodType.setStatus(1);
		foodService.insertFoodType(foodType);

		return Response.success("食品规格添加成功");
	}

	// 食品规格列表
	@RequestMapping(value = "type/list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String type_list(HttpServletRequest request) throws Exception {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		Integer page, pageSize;
		QueryFoodCategory queryFoodCategory = new QueryFoodCategory();

		String sortBy = request.getParameter("sortBy");
		String sortMethod = request.getParameter("sortMethod");

		page = NumberUtils.toInt(request.getParameter("page_num"));
		pageSize = NumberUtils.toInt(request.getParameter("page_size"));

		if (StringUtils.isBlank(sortBy))
			sortBy = "update_time";

		if (StringUtils.isBlank(sortMethod))
			sortMethod = "desc";

		queryFoodCategory.setSortBy(sortBy);
		queryFoodCategory.setSortMethod(sortMethod);
		queryFoodCategory.setPage(page);
		queryFoodCategory.setPageSize(pageSize);
		queryFoodCategory.setCompanyId(account.getCompanyId());
		queryFoodCategory.setStatus(1);

		QueryResult result = foodService.queryFoodType(queryFoodCategory);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("page", result.getPage());
		map.put("pageSize", result.getPageSize());
		map.put("totalRecord", result.getTotalRecord());
		map.put("data", result.getData());

		return Response.success(map);
	}

	// 编辑食品规格
	@RequestMapping(value = "type/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String type_edit(HttpServletRequest request) throws Exception {
		
		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String unit = request.getParameter("unit");
		String id = request.getParameter("id");

		if (StringUtils.isEmpty(unit)) {
			return Response.error(MessageCode.NO_DATA, "未知的请求数据");
		}

		FoodType foodType = new FoodType();
		foodType.setId(Integer.parseInt(id));
		foodType.setUnit(unit);
		foodType.setOperatorId(account.getOperatorId());
		foodService.updateFoodTypeById(foodType);

		return Response.success("食品规格修改成功!");
	}
	
	// 删除食品规格
	@RequestMapping(value = "type/delete", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String type_delete(HttpServletRequest request) throws Exception {

        Account account = this.getCommonUserAccount(request);
        if(account == null){
            return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
        }

    	String id = request.getParameter("id");
    	
    	List<Food> list = foodService.findFoodByUnitId(Integer.parseInt(id));
		for(Food item : list){
			if(item.getStatus() == 1 ){
				return Response.error(MessageCode.REQUEST_ERROR);
			}
		}
		
		foodService.deleteFoodTypeById(account, Integer.parseInt(id));

		return Response.success("食品分类删除成功!");
	}

	// 添加食品
	@RequestMapping(value = "add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String add(HttpServletRequest request)throws JsonProcessingException {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}
		
		String name = StringUtils.trimToEmpty(request.getParameter("name"));
		String weight = StringUtils.trimToEmpty(request.getParameter("weight"));
		String categoryId = StringUtils.trimToEmpty(request
				.getParameter("category_id"));
		String goodsPrice = StringUtils.trimToEmpty(request
				.getParameter("goods_price"));
		String originalPrice = StringUtils.trimToEmpty(request
				.getParameter("original_price"));
		String description = StringUtils.trimToEmpty(request
				.getParameter("description"));

		if (StringUtils.isEmpty(name) || StringUtils.isEmpty(weight)
				|| Integer.parseInt(categoryId) <= 0
				|| StringUtils.isEmpty(goodsPrice) || StringUtils.isEmpty(originalPrice)) {
			return Response.error(MessageCode.REQUEST_ERROR, "未知的请求数据");
		}

		

		try {
			Integer.parseInt(weight);
			NumberUtils.toDouble(goodsPrice);
			NumberUtils.toDouble(originalPrice);
		} catch (Exception e) {
			return Response.error(MessageCode.NO_DATA, "输入权重值有误");
		}

		Food food = new Food();
		food.setCompanyId(account.getCompanyId());
		food.setCategoryId(NumberUtils.toInt(categoryId));
		food.setOperatorId(account.getOperatorId());
		food.setDescription(description);
		food.setGoodsPrice(NumberUtils.toDouble(goodsPrice));
		food.setOriginalPrice(NumberUtils.toDouble(originalPrice));
		food.setName(name);
		food.setStatus(1);
		food.setWeight(NumberUtils.toInt(weight));
		foodService.insertFood(request, food);

		return Response.success("食品创建成功");
	}

	// 食品列表
	@RequestMapping(value = "list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String list(HttpServletRequest request) throws Exception {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		Integer page, pageSize, categoryId = null;
		QueryFoodCategory queryFoodCategory = new QueryFoodCategory();

		String sortBy = request.getParameter("sortBy");
		String sortMethod = request.getParameter("sortMethod");

		String category_id = request.getParameter("category_id");

		page = NumberUtils.toInt(request.getParameter("page_num"));
		pageSize = NumberUtils.toInt(request.getParameter("page_size"));

		if (StringUtils.isBlank(sortBy))
			sortBy = "weight";

		if (StringUtils.isBlank(sortMethod))
			sortMethod = "desc";

		queryFoodCategory.setSortBy(sortBy);
		queryFoodCategory.setSortMethod(sortMethod);
		queryFoodCategory.setPage(page);
		queryFoodCategory.setPageSize(pageSize);
		queryFoodCategory.setCompanyId(account.getCompanyId());

		if (StringUtils.isBlank(category_id)) {

		} else {
			categoryId = NumberUtils.toInt(category_id);
		}

		queryFoodCategory.setCategoryId(categoryId);
		queryFoodCategory.setStatus(1);
		
		QueryResult result = foodService.queryFood(queryFoodCategory);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("page", result.getPage());
		map.put("pageSize", result.getPageSize());
		map.put("totalRecord", result.getTotalRecord());
		map.put("data", result.getData());

		return Response.success(map);
	}

	// 编辑食品
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String edit(HttpServletRequest request) throws Exception {

        Account account = this.getCommonUserAccount(request);
        if(account == null){
            return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
        }

    	String json = request.getParameter("json");
        
		if (StringUtils.isBlank(json)) {
			return Response.error(MessageCode.JSON_WRONG);
		}
		
		HashMap<String, Object> data = new HashMap<String, Object>();
		try {
			data = (HashMap<String, Object>) JSONParser.parse(json,
					new HashMap<String, Object>().getClass());
		} catch (Exception e) {
			e.printStackTrace();
			return Response.error(MessageCode.JSON_WRONG);
		}
		
        Iterator<Entry<String, Object>> itera = data.entrySet().iterator();  
        while(itera.hasNext()){  
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>)itera.next();  
            if(entry.getValue() == null || entry.getValue().equals("")){ 
            	return Response.error(MessageCode.PARAMETER_WRONG);  
            }  
        } 

		foodService.updateFoodById(account, data);

		return Response.success("食品修改成功");
	}

	// 编辑食品
	@RequestMapping(value = "delete", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String delete(HttpServletRequest request) throws Exception {

        Account account = this.getCommonUserAccount(request);
        if(account == null){
            return Response.error(MessageCode.ERROR_NO_LOGIN,"未登录");
        }

    	String id = request.getParameter("id");
        
		foodService.deleteFoodById(account, Integer.parseInt(id));

		return Response.success("食品删除成功!");
	}
	
	// App端食品接口
	@RequestMapping(value = "foodDetailList", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String food_detail_list(HttpServletRequest request) throws Exception {

		StoreAppAccount storeAppAccount = this.getStoreAppAccount(request);
		if (storeAppAccount == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}
		
		StoreInfo storeInfo = storeManagerService.findStoreInfoById(storeAppAccount.getStoreInfoId());
		
		if(storeInfo == null){
			return Response.error(MessageCode.STORE_ID_WRONG);
		}

		String json = "";
		if(storeInfo.getCompanyId() > 0){
			json = foodService.findAllFood(storeInfo.getCompanyId());
			return json;
		}else{
			return Response.error(MessageCode.NO_DATA);
		}
	}

}
